//
//  WBTitleButton.swift
//  传智微博
//
//  Created by zuxi li on 2017/3/23.
//  Copyright © 2017年 lingtu. All rights reserved.
//

import UIKit

class WBTitleButton: UIButton {

    
    /// 重载构造函数
    ///
    /// - Parameter title: 如果title是nil就显示首页，如果不为nil就显示title和箭头图像
    init(title: String?) {
        super.init(frame: CGRect())
        if title == nil {
            setTitle("首页", for: .normal)
        } else {
            setTitle(title! + " ", for: .normal)
            setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: .normal)
        sizeToFit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 重新布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 判断title和imageView是否同时存在
        guard let titleLabel = titleLabel,
            let imageView = imageView else {
            return
        }
        
        // 将label的x向左移动image的宽度  将image向右移动title的宽度
        let x1 = titleLabel.frame.width
        let x2 = imageView.bounds.width
        titleEdgeInsets = UIEdgeInsetsMake(0, -x2, 0, x2)
        imageEdgeInsets = UIEdgeInsetsMake(0, x1, 0, -x1)

        
    }

}
